#define  _CRT_SECURE_NO_WARNINGS
class Solution {
public:
    int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) {
        queue<pair<int, int>> q;
        int ret = 0;
        int m = maze.size(), n = maze[0].size();
        int er = entrance[0], ec = entrance[1];
        q.push({ er, ec });
        vector<vector<bool>> visit(m, vector<bool>(n, false));
        visit[er][ec] = true;
        while (q.size())
        {
            ret++;
            int size = q.size();
            for (int i = 0; i < size; i++)
            {
                auto [r, c] = q.front();
                q.pop();
                for (int j = 0; j < 4; j++)
                {
                    static int dx[4] = { 0,0,1,-1 };
                    static int dy[4] = { 1,-1,0,0 };
                    int x = r + dx[j];
                    int y = c + dy[j];
                    if (x >= 0 && x < m && y >= 0 && y < n
                        && maze[x][y] == '.' && !visit[x][y])
                    {
                        if (x == 0 || y == 0 || x == m - 1 || y == n - 1) return ret;
                        q.push({ x, y });
                        visit[x][y] = true;
                    }
                }
            }
        }
        return -1;
    }
};